package la.iok.hzsvn.lewin.movie.cloud.controller;

import la.iok.hzsvn.lewin.cloud.invoker.service.RestServiceInvoker;
import la.iok.hzsvn.lewin.movie.cloud.model.TokenInfo;
import la.iok.hzsvn.share.response.SingleDataResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("tokens")
public class TokenController {
    private static final Logger logger = LoggerFactory.getLogger(TokenController.class);
    @Autowired
    private RestServiceInvoker restServiceInvoker;

    /**
     * 刷新令牌
     * @param refreshToken 刷新令牌参数
     * @return 令牌响应
     */
    @RequestMapping("refresh")
    public SingleDataResponse<TokenInfo> refresh(@RequestBody String refreshToken){
        // { grant_type: 'refresh_token', refresh_token: refresh_token, client_id: 'lewin', client_secret: 'lwp2wd' }
        if(logger.isDebugEnabled()){
            logger.debug("refreshToken={}", refreshToken);
        }
        Map<String,String> params = new HashMap<>();
        params.put("refreshToken",refreshToken);
        params.put("grantType","refresh_token");
        params.put("clientId","lewin");
        params.put("clientSecret","lwp2wd");
        TokenInfo token = restServiceInvoker.postForObject("authserver","/oauth/token?refresh_token={refreshToken}&grant_type={grantType}&client_id={clientId}&client_secret={clientSecret}",null, TokenInfo.class,params);
        return new SingleDataResponse<>(token);
    }
}
